package org.jaaksi.kottlindemo.anim

import android.animation.ObjectAnimator
import android.os.Bundle
import android.view.animation.TranslateAnimation
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.animation.addListener
import androidx.core.animation.doOnEnd
import androidx.core.view.updateLayoutParams
import org.jaaksi.kottlindemo.databinding.ActivityTestAnimBinding
import org.jetbrains.anko.dip
import org.jetbrains.anko.toast

class TestAnimActivity : AppCompatActivity() {
    private val binding by lazy { ActivityTestAnimBinding.inflate(layoutInflater) }
    private val dp_100 by lazy { dip(100).toFloat() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.btnToast.setOnClickListener {
//            objAnim?.end() // view直接到动画结束的位置
//            objAnim?.cancel() // view停在动画当前的位置，cancel也会调用endAnimation，所以也会回调end
//            binding.btnClick.animate().cancel()
        }
        binding.btnClick.setOnClickListener {
            test4()
        }
    }

    private var objAnim: ObjectAnimator? = null
    private fun test3() {
        // 无法用view.animate().cancel()取消
        objAnim = ObjectAnimator.ofFloat(binding.btnClick, "translationX", dp_100)
            .setDuration(5000)
            .apply {
                doOnEnd {
                    toast("Anim end")
                }
            }
        objAnim?.start()
//        finish()
    }

    private fun test1() {
        // 属于android.view.animation,不能改变真实位置。可以通过view.clearAnimation()取消动画
        val anim = TranslateAnimation(0f, dp_100, 0f, 0f)
        anim.duration = 5000
        // //设置动画结束后效果保留
        anim.fillAfter = true
        binding.btnClick.startAnimation(anim)

        binding.btnClick.updateLayoutParams<ConstraintLayout.LayoutParams> {
            topMargin = 10
        }
    }

    private fun test4() {
        // 属于android.animation
        // 使用clearAnimation无法清除
        binding.btnClick.animate().translationX(dp_100).setDuration(5000).start()
    }

    private fun test2() {
        // 这个会改变View的真实位置
        binding.btnClick.translationX = dp_100
        binding.btnClick.translationY = dp_100
    }


}